package com.fsc.comadapoc1.application
{
	import com.fsc.comadapoc1.domain.PortfolioModel;
	import com.fsc.comadapoc1.domain.UserModel;
	import com.fsc.comadapoc1.events.LoadPortfolioFundsEvent;
	import com.fsc.comadapoc1.events.PortfolioSearchEvent;
	import com.fsc.comadapoc1.utils.PortfolioUtil;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.remoting.RemoteObject;
	import mx.utils.ArrayUtil;

	[Event(name="portfolioFundsLoadComplete",type="com.fsc.comadapoc1.events.LoadPortfolioFundsEvent")]
	[ManagedEvents(names="portfolioFundsLoadComplete")]
	public class GetPortfolioFundsCommand extends EventDispatcher
	{
		
		public var searchTerm:String;
		
		[Inject(id="portfolioService")]
		public var service:RemoteObject;
		
		/**
		 * Contains objects to manage portfolios
		 */ 
		[Inject]
		[Bindable]
		public var model:PortfolioModel;
		
		
		[Inject]
		[Bindable]
		public var userModel:UserModel;
		
		private var pendingSearchTerm : String;
		private var inited:Boolean = false;
		
		public function init():void{
			trace("Initializing Get portfolio funds Command");
			
			inited = true;
		}
		
		
		public function execute(event:LoadPortfolioFundsEvent):AsyncToken {
			if(!inited){
				init();
			}
			searchTerm = event.searchTerm;
			//search(term);
			return service.GetPortfolioFunds( userModel.guid,model.currentPortfolio.id) as AsyncToken;
		}
		
		/******************************************
		 *  Result handler 
		 */
		public function result(data:Object):void
		{
			var searchCompleteEvent:LoadPortfolioFundsEvent = new LoadPortfolioFundsEvent(LoadPortfolioFundsEvent.LOAD_COMPLETE);
	
			if ( data.Results != null)
			{
				trace("Setting the get funds results");
				model.currentPortfolio.funds.source = ArrayUtil.toArray(data.Results);
			
			}
			else
			{
				trace("SearchCommand: Clearing Results");
				searchTerm = null;
			}
			dispatchEvent(searchCompleteEvent);
			model.searchResults.enableAutoUpdate();
			
			
		}
		
		/******************************************
		 *  Fault handler in case the request failed. 
		 */
		public function error (fault:FaultEvent, trigger:LoadPortfolioFundsEvent) : void {
			//need to add some logging here
			Alert.show(fault.fault.message,fault.fault.faultDetail);
		}  
		
	}
}